package cn.iocoder.yudao.module.signature.handler;

import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.signature.appconnect.exception.AppStoreConnectException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.ws.rs.client.ResponseProcessingException;

/**
 * @author liujq
 * @date 20241223 21:02
 */
@RestControllerAdvice
@AllArgsConstructor
@Slf4j
public class AppleExceptionHandler {

    @ExceptionHandler(value = ResponseProcessingException.class)
    public CommonResult<?> responseProcessingExceptionHandler(ResponseProcessingException ex) {
        Throwable cause = ex.getCause();
        String message = "调用接口失败";
        if (cause instanceof AppStoreConnectException) {
            AppStoreConnectException appStoreConnectException = (AppStoreConnectException) cause;
            message = "调用苹果接口失败,错误码:【" + appStoreConnectException.getErrorResponse().getErrors().get(0).getCode() + "】,错误信息:【" + appStoreConnectException.getErrorResponse().getErrors().get(0).getDetail() + "】";
        }
        log.warn("[responseProcessingExceptionHandler]", ex);
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), message);
    }
}
